
package com.nhc.activity_fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.AlarmClock;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.sdk.android.feedback.impl.FeedbackAPI;
import com.astrob.activitys.AppContext;
import com.astrob.activitys.IndoorMapActivity;
import com.astrob.model.Msg;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.astrob.view.BaseViewHolder;
import com.nhc.view.MyGridView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import zuo.biao.library.base.BaseAdapter;
import zuo.biao.library.base.BaseFragment;
import zuo.biao.library.model.Entry;
import zuo.biao.library.util.CommonUtil;
import zuo.biao.library.util.DataKeeper;
import zuo.biao.library.util.Log;
import zuo.biao.library.util.StringUtil;

import static zuo.biao.library.ui.CutPictureActivity.REQUEST_CODE_CAMERA;

//Android Intent 用法全面总结
//https://www.oschina.net/code/snippet_54100_7587

public class MoreFragment extends BaseFragment {
    private final String TAG = "MoreFragment";

    //与Activity通信<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 创建一个Fragment实例
     *
     * @return
     */
    public static MoreFragment createInstance() {
        return new MoreFragment();
    }

    Handler mFHandler = null;// for 双击全屏显示

    public void setFatherHandler(Handler fHandler) {
        mFHandler = fHandler;
    }
    //与Activity通信>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        setContentView(R.layout.more_fragment);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

        return view;//返回值必须为view
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private MyGridView lvMoreGird;

    //示例代码>>>>>>>>
    @Override
    public void initView() {//必须在onCreateView方法内调用
        lvMoreGird = (MyGridView) findViewById(R.id.lvMoreGird);
    }

    //示例代码<<<<<<<<
    private GridAdapter adapter;
    //示例代码>>>>>>>>

    /**
     * 示例方法 ：显示列表内容
     *
     * @param list
     */
    private void setList(List<Entry<Integer, String>> list) {
        if (adapter == null) {
            adapter = new GridAdapter(context);
            lvMoreGird.setAdapter(adapter);
        }
        adapter.refresh(list);
    }
    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //示例代码<<<<<<<<
    private List<Entry<Integer, String>> list;
//    private final int[] GRID_IDS = {
//            R.drawable.more_point, R.drawable.more_line, R.drawable.more_track,
//            R.drawable.more_position, R.drawable.more_settings, R.drawable.more_search,
//            R.drawable.more_media, R.drawable.more_warning, R.drawable.more_pressure,
//            R.drawable.settings_about, R.drawable.settings_altimeter, R.drawable.settings_coordinates,
//            R.drawable.settings_direction, R.drawable.settings_function, R.drawable.settings_map,
//            R.drawable.settings_save, R.drawable.settings_settings, R.drawable.settings_track,
//            R.drawable.settings_about, R.drawable.settings_altimeter};

    //    private final int[] GRID_ICONFONT_IDS = {
//            R.string.fonticon_more_navipt, R.string.fonticon_more_naviline, R.string.fonticon_more_navitrack,
//            R.string.fonticon_more_weizhi, R.string.fonticon_more_set, R.string.fonticon_more_search,
//            R.string.fonticon_more_cehui, R.string.fonticon_more_warningpt, R.string.fonticon_more_qiyajilu,
//            R.string.fonticon_more_yulie, R.string.fonticon_more_daorudaochu, R.string.fonticon_more_dianjiaozheng,
//            R.string.fonticon_more_riyue, R.string.fonticon_more_paomao};
//
//    private final String[] GRID_NAMES = {
//            "航点", "航线", "航迹",
//            "位置", "设置", "查找",
//            "测绘", "警告点", "气压记录",
//            "渔猎", "导入导出", "点矫正",
//            "日月", "抛锚"};
    private final int[] GRID_ICONFONT_IDS = {
            R.string.fonticon_more_navipt, R.string.fonticon_more_naviline, R.string.fonticon_more_navitrack,
            R.string.fonticon_more_weizhi, R.string.fonticon_more_set, R.string.fonticon_more_search,
            R.string.fonticon_more_cehui, R.string.fonticon_more_warningpt, R.string.fonticon_more_qiyajilu,
            R.string.fonticon_more_riyue, R.string.fonticon_more_daorudaochu, R.string.fonticon_more_paomao
            , R.string.fonticon_more_osm, R.string.fonticon_more_yhfk};


    private int[] GRID_INDEXS = new int[]{
            0, 1, 2,
            3, 4, 5,
            6, 7, 8,
            9, 10, 11,
            12, 13};

    private final int[] GRID_ICONFONT_IDS_240x320 = {
            R.string.fonticon_more_navipt, R.string.fonticon_more_naviline, R.string.fonticon_more_navitrack,
            R.string.fonticon_more_weizhi, R.string.fonticon_more_set, R.string.fonticon_more_search,
            R.string.fonticon_more_cehui, R.string.fonticon_more_warningpt, R.string.fonticon_more_qiyajilu,
            R.string.fonticon_more_riyue, R.string.fonticon_more_daorudaochu, R.string.fonticon_more_paomao,
            R.string.fonticon_more_osm, R.string.fonticon_more_yhfk, R.string.fonticon_more_rili, R.string.fonticon_more_jisuanqi,
            R.string.fonticon_more_miaobiao, R.string.fonticon_more_tupian, R.string.fonticon_more_shoudian
    };

    private int[] GRID_INDEXS_240x320 = new int[]{
            0, 1, 2,
            3, 4, 5,
            6, 7, 8,
            9, 10, 11,
            12, 13, 14,
            15, 16, 17,18};

    protected List<Entry<Integer, String>> getList() {
        list = new ArrayList<Entry<Integer, String>>();
        int num = GRID_ICONFONT_IDS.length;
        if (SysUtils.getInstance().is240x320) {
            num = GRID_ICONFONT_IDS_240x320.length;
        }
        for (int i = 0; i < num; i++) {
            list.add(new Entry<Integer, String>(i, ""));
        }
        return list;
    }

    //示例代码>>>>>>>>>
    @Override
    public void initData() {//必须在onCreateView方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        list = getList();
        setList(list);
        //示例代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreateView方法内调用
        lvMoreGird.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                onSelectGrid(position);
            }
        });

    }

    private void onSelectGrid(int position) {
        lvMoreGird.setSelection(-1);
        doFounc(adapter.getItem(position).getKey());
        adapter.notifyDataSetChanged();
    }

    private void doFounc(Integer gridIndex) {
        lvMoreGird.setSelection(gridIndex);
        switch (gridIndex) {
            default:
            case 0:
                gridIndex = 0;
                toActivity(NaviPtActivity.createIntent(getContext()), 0);
                break;
            case 1:
                toActivity(NaviLineActivity.createIntent(getContext()), 1);
                break;
            case 2:
                toActivity(NaviTrackActivity.createIntent(getContext()), 2);
                break;
            case 3:
                toActivity(LocationActivity.createIntent(getContext()), 3);
//                toActivity(IndoorMapActivity.createIntent(getContext()), 13);
                break;
            case 4:
                toActivity(SystemSettingActivity.createIntent(getContext()), 4);
                break;
            case 5:
                toActivity(SearchTypeActivity.createIntentfromMore(getContext()), 5);
                break;
            case 6:
                toActivity(MeasureActivity.createIntent(getContext()), 6);
                break;
            case 7:
                toActivity(WarningPointActivity.createIntent(getContext()), 7);
                break;
            case 8:
                toActivity(QiyaActivity.createIntent(getContext()), 8);
                break;
            case 9:
//                toActivity(FishHuntActivity.createIntent(getContext()), 9);
                toActivity(RiyueActivity.createIntent(getContext()), 9);
                break;
            case 10:
                toActivity(ImportExportActivity.createIntent(getContext()), 10);
                break;
            case 11:
//                toActivity(DJZActivity.createIntent(getContext()), 11);
                toActivity(PaomaoActivity.createIntent(getContext()), 11);
                break;
            case 12:
                toActivity(MapSelectTabActivity.createIntent(getContext()), 12);
                break;
            case 13:
                //用户反馈
                if (Utils.isNetConnected(getContext())) {
                    FeedbackAPI.openFeedbackActivity();
                } else {
                    showShortToast("请先连接网络！");
                }
                break;
            case 14:
                onCalendar();
                break;
            case 15: {
                //计算器
                Intent intent = new Intent();
                intent.setClassName("com.android.calculator2",
                        "com.android.calculator2.Calculator");
                startActivity(intent);
            }
            break;
            case 16: {
                //秒表
                toActivity(MiaoBiaoActivity.createIntent(getContext()), 15);

//                Intent intent = new Intent();
//                intent.setClassName("com.android.deskclock",
//                        "com.android.deskclock.DeskClock");
//                startActivity(intent);
            }
            break;
            case 17: {
                //相册
                toActivity(PhotoAlbumActivity.createIntent(getContext()), 17);
//                Intent i = new Intent(Intent.ACTION_PICK,
//                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                startActivityForResult(i, 17);
            }
            break;
            case 18: {
//                Intent i = new Intent(Settings.ACTION_SETTINGS);
//                startActivityForResult(i, 18);
                onSDT();
            }
            break;
        }

//        showShortToast("选择了 " + GRID_NAMES[gridIndex]);
    }

    private void onSDT() {
        if (camera == null) {
            camera = Camera.open();
        }
        Parameters parameters = camera.getParameters();
        if (parameters == null) {
            return;
        }
        String value = parameters.getFlashMode();
        if (value.compareToIgnoreCase(Parameters.FLASH_MODE_TORCH) == 0) {
            parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
        } else {
            parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
        }

        camera.setParameters(parameters);
    }

    public void startTimer(String message, int seconds) {
        Intent intent = new Intent(AlarmClock.ACTION_SET_TIMER)
                .putExtra(AlarmClock.EXTRA_MESSAGE, message)
                .putExtra(AlarmClock.EXTRA_LENGTH, seconds)
                .putExtra(AlarmClock.EXTRA_SKIP_UI, true);
        if (intent.resolveActivity(getContext().getPackageManager()) != null) {
            startActivity(intent);
        }
    }

    /**
     * 照相获取图片
     */
    public void selectPicFromCamera() {
        if (!CommonUtil.isExitsSdcard()) {
            showShortToast("SD卡不存在，不能拍照");
            return;
        }

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 指定调用相机拍照后照片的储存路径
        File cameraFile = new File(DataKeeper.imagePath, "photo" + System.currentTimeMillis() + ".jpg");
        cameraFile.getParentFile().mkdirs();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
        toActivity(intent, REQUEST_CODE_CAMERA);
    }

    void onCalendar() {
//        Intent intent = new Intent(Intent.ACTION_INSERT);
//        intent.setData(CalendarContract.Events.CONTENT_URI);
//        startActivity(intent);
        Intent intent = new Intent();
        intent.setClassName("com.android.calendar",
                "com.android.calendar.AllInOneActivity");
        startActivity(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Msg.NAVI_TO_DEST) {
            if (mFHandler != null) {
                mFHandler.sendEmptyMessage(Msg.NAVI_TO_DEST);
            }
            return;
        }

        if (resultCode == Msg.NAVI_BY_ROUTE) {
            if (mFHandler != null) {
                mFHandler.sendEmptyMessage(Msg.NAVI_BY_ROUTE);
            }
            return;
        }

        if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK) {
//            Bitmap thumbnail = data.getParcelable("data");
        }
    }

    public void doKeyUp() {
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    //Event事件区(只要存在事件监听代码就是)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    public class GridAdapter extends BaseAdapter<Entry<Integer, String>> {
        private final String TAG = "GridAdapter";

        public GridAdapter(Activity context) {
            this(context, R.layout.more_grid_item);
        }

        public GridAdapter(Activity context, int layoutRes) {
            super(context);
            setLayoutRes(layoutRes);
        }

        private int layoutRes;//item视图资源

        public void setLayoutRes(int layoutRes) {
            this.layoutRes = layoutRes;
        }

        private boolean hasName = true;//是否显示名字

        public GridAdapter setHasName(boolean hasName) {
            this.hasName = hasName;
            return this;
        }

        private boolean hasCheck = false;//是否使用标记功能

        public GridAdapter setHasCheck(boolean hasCheck) {
            this.hasCheck = hasCheck;
            return this;
        }

        //item标记功能，不需要可以删除<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        private HashMap<Integer, Boolean> hashMap;//实现选中标记的列表，不需要可以删除。这里可用List<Integer> checkedList代替

        public boolean getItemChecked(int position) {
            if (hasCheck == false) {
                Log.e(TAG, "<<< !!! hasCheck == false  >>>>> ");
                return false;
            }
            return hashMap.get(position);
        }

        public void setItemChecked(int position, boolean isChecked) {
            if (hasCheck == false) {
                Log.e(TAG, "<<< !!! hasCheck == false >>>>> ");
                return;
            }
            hashMap.put(position, isChecked);
            notifyDataSetChanged();
        }
        //item标记功能，不需要可以删除>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


        public int selectedCount = 0;

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        layoutRes, parent, false);
            }

            ImageView iv_item = BaseViewHolder.get(convertView, R.id.iv_item);
            TextView tv_item = BaseViewHolder.get(convertView, R.id.tv_item);
            TextView iv_check = BaseViewHolder.get(convertView, R.id.iv_check);
            TextView tv_item2 = BaseViewHolder.get(convertView, R.id.tv_item2);
            tv_item2.setTypeface(AppContext.getInstances().getIconfont());
            TextView tv_focus = BaseViewHolder.get(convertView, R.id.tv_focus);

            iv_check.setTypeface(AppContext.getInstances().getIconfont());
            iv_item.setVisibility(View.GONE);
            tv_item2.setVisibility(View.VISIBLE);

            final Entry<Integer, String> kvb = getItem(position);
            int gridIndex = kvb.getKey();
            int num = GRID_ICONFONT_IDS.length;
            if (SysUtils.getInstance().is240x320) {
                num = GRID_ICONFONT_IDS_240x320.length;
            }
            if (gridIndex < 0 || gridIndex >= num) {
                gridIndex = 0;
            }
            String[] GRID_NAMES = getResources().getStringArray(R.array.grid_names);
            if (SysUtils.getInstance().is240x320) {
                GRID_NAMES = getResources().getStringArray(R.array.grid_names_240x320);
            }

            final String name = GRID_NAMES[gridIndex];

            if (hasName) {
                tv_item.setText(StringUtil.getTrimedString(name));
            }

            int resId = 0;
            if (SysUtils.getInstance().is240x320) {
                resId = GRID_ICONFONT_IDS_240x320[gridIndex];
            } else {
                resId = GRID_ICONFONT_IDS[gridIndex];
            }

            tv_item2.setText(resId);

            if (hasCheck) {
                iv_check.setVisibility(View.VISIBLE);
                iv_check.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setItemChecked(position, !getItemChecked(position));
                    }
                });
            }

            int select = lvMoreGird.getSelectedItemPosition();
            if (select == position && SysUtils.getInstance().is240x320) {
                tv_focus.setVisibility(View.VISIBLE);
            } else {
                tv_focus.setVisibility(View.GONE);
            }

            return convertView;
        }

        /**
         * 刷新列表
         *
         * @param list
         */
        @Override
        public synchronized void refresh(List<Entry<Integer, String>> list) {
            if (list != null && list.size() > 0) {
                initList(list);
            }
            if (hasCheck) {
                selectedCount = 0;
                for (int i = 0; i < this.list.size(); i++) {
                    if (getItemChecked(i) == true) {
                        selectedCount++;
                    }
                }
            }
            notifyDataSetChanged();
        }

        /**
         * 标记List<String>中的值是否已被选中。
         * 不需要可以删除，但“this.list = list;”这句
         * 要放到constructor【这个adapter只有ModleAdapter(Context context, List<Object> list)这一个constructor】里去
         *
         * @param list
         * @return
         */
        @SuppressLint("UseSparseArrays")
        private void initList(List<Entry<Integer, String>> list) {
            this.list = list;
            if (hasCheck) {
                hashMap = new HashMap<Integer, Boolean>();
                if (list != null) {
                    for (int i = 0; i < list.size(); i++) {
                        hashMap.put(i, false);
                    }
                }
            }
        }

    }

//    http://www.apkbus.com/android-182590-1-1.html

// 根据包名跳转到系统自带的应用程序信息界面
//    Uri packageURI = Uri.parse("package:" + "com.tencent.WBlog");
//    Intent intent =  new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,packageURI);
//    startActivity(intent);

// 跳转系统的蓝牙设置界面
//    Intent intent =  new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);

//  跳转日期时间设置界面
//    Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);

// 跳转系统的辅助功能界面
//    Intent intent =  new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);

// 跳转手机状态界面
//    Intent intent =  new Intent(Settings.ACTION_DEVICE_INFO_SETTINGS);

// 跳转到设置界面
//    Intent intent =  new Intent(Settings.ACTION_SETTINGS);
// 跳转到声音设置界面
//    Intent intent =  new Intent(Settings.ACTION_SOUND_SETTINGS);

    private Camera camera;

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (camera != null) {
            camera.release();
            camera = null;
        }
    }

}